package cn.arikeky.org.service.impl;


import cn.arikeky.basic.query.BaseQuery;
import cn.arikeky.basic.service.impl.BaseServiceImpl;;
import cn.arikeky.basic.util.MD5Utils;
import cn.arikeky.basic.util.PageList;
import cn.arikeky.basic.util.StrUtils;
import cn.arikeky.org.domain.Employee;
import cn.arikeky.org.mapper.EmployeeMapper;
import cn.arikeky.org.service.IEmployeeService;
import cn.arikeky.user.domain.Logininfo;
import cn.arikeky.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        // 因为默认的密码是明文，所以需要对密码加密
        initEmployee(employee);
        // 将employee对象中的数据拷贝到logininfo对象中
        Logininfo logininfo = employeeLogininfo(employee);
        // 保存logininfo数据
        logininfoMapper.add(logininfo);
        // 将logininfo的主键设置为employee的外键保存
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.add(employee);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    public void delete(Long id) {
        super.delete(id);
    }
    
    // 封装添加的方法
    private void initEmployee(Employee employee){
        // 获取颜值
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        // 根据盐值进行加密，并设置到对象中
        String md5Pow = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pow);
    }
    // 将employee对象当中的数据拷贝到logininfo表中，并返回对象
    private Logininfo employeeLogininfo(Employee employee){
        // 拷贝数据
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        // 设置用户类型为员工
        logininfo.setType(0);
        // 返回logininfo对象
        return logininfo;
    }

    @Override
    public List<Employee> findAll() {
        return super.findAll();
    }

    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        return super.queryByPage(query);
    }

    @Override
    public Employee selectByLogininfo(Long id) {
        return employeeMapper.selectByLogininfo(id);
    }

    @Override
    public List<Employee> empList(Long id) {
        return employeeMapper.empList(id);
    }

    @Override
    public Employee findByLogId(Long id) {
        return employeeMapper.findByLogId(id);
    }

}
